import request from '@/utils/request'
function packageFormData(data) {
    if (!data) return;
    let formData = new FormData();
    for (const key in data) {
        formData.append(key, data[key]);
    }
    return formData;
}
export function commonQuery(baseUrl) {
    function getById(id) {
        return request.get(baseUrl + '/getById', {
            params: { id }
        })
    }
    function empty() {
        return request.get(baseUrl + '/empty')
    }
    function list(options) {
        return request.post(baseUrl + '/list', options)
    }
    function page(options) {
        return request.post(baseUrl + '/page', options)
    }
    function save(data) {
        return request.put(baseUrl + '/save', data)
    }
    function update(data) {
        return request.put(baseUrl + '/update', data)
    }
    function saveOrUpdate(data) {
        return request.put(baseUrl + '/saveOrUpdate', data)
    }
    function removeByIds(ids) {
        return request.delete(baseUrl + '/removeByIds', { data: ids })
    }
    function importTemplate({ columns=[], fileName='导入模板.xlsx', sheet='sheet1', option={} }) {
        request.post(baseUrl + '/importTemplate', { columns, sheet, option },
            { responseType: 'blob' }).then(data => {
            downBinary({data, fileName})
        })
    }
    function importData({ columns = [], sheet= 'sheet1', file = null }) {
        return request({
            url: baseUrl + '/importData',
            method: 'post',
            headers: {
                "Content-Type": "multipart/form-data",
            },
            data: packageFormData({ columns: JSON.stringify(columns), sheet, file })
        })
    }
    function downBinary({data=[], fileName='download.xlsx'}) {
        /* 兼容ie内核，360浏览器的兼容模式 */
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            const blob = new Blob([data]);
            window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
            /* 火狐谷歌的文件下载方式 */
            var blob = new Blob([data]);
            var downloadElement = document.createElement('a');
            var href = window.URL.createObjectURL(blob);
            downloadElement.href = href;
            downloadElement.download = fileName;
            document.body.appendChild(downloadElement);
            downloadElement.click();
            document.body.removeChild(downloadElement);
            window.URL.revokeObjectURL(href);
        }
    }
    return {
        getById,
        empty,
        list,
        page,
        save,
        update,
        saveOrUpdate,
        removeByIds,
        importTemplate,
        importData,
        downBinary,
        baseUrl
    }
}


